import { ref ,unref} from 'vue'
import store from '@/store/index.js';
import {dictTypeAapi} from '@/api/dictdata.js'

// 按照惯例，组合式函数名以“use”开头
export function useDict(...args) {

   const res = ref({}); 
   
   // 立即执行函数
   // (function())()
   
    return (() => {
      //循环遍历集合中的值(值，下标)
      args.forEach((dictType, index) => {
        //  var res={dictType:[]}
        res.value[dictType] = [];
        //在vuex中查询，是否已经这个key了
        
        const dictAllData = store.getters['datadict/getAllDict']
        
        let findIndex=-1;  
        for (let i = 0; i < dictAllData.length; i++) {
          if (dictAllData[i].key == dictType) {
           findIndex=i;
           break;
          }
        }  
        
        if (findIndex>=0) {
          res.value[dictType] = dictAllData[findIndex].value;
        } else {
          //查询数据库
          dictTypeAapi(dictType).then(resp => {
            const dataList=resp.data.map(p => ({ label: p.dictLabel, value: p.dictValue, elTagType: p.listClass, elTagClass: p.cssClass }))
            res.value[dictType] = dataList
            
            //赋值给vuex 
            const data={
              'key': dictType,
              'value': dataList
            } 
            //vuex 的commit不允许传2个值
            store.commit('datadict/setDict',data )  
          })
        }
      })
      return toRefs(res.value);
    })() 
    
}
